package com.ciwong.epaper.modules.login;

import android.text.TextUtils;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.LoginInfo;
import com.ciwong.epaper.bean.UserAccountInfo;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.util.AESCBCUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.libs.utils.volley.HttpRequest;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseConstants;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 登录数据逻辑层实现
 * Created by lqi on 2017/2/22.
 */
public class LoginModelImpl implements LoginContract.LoginModel {
    @Override
    public void login(final EApplication application, String usernameStr, final String passwordBefor, String uuid, String captchaCode, final LoginFinishedListener listener, final boolean isMobile) {
        final String password = AESCBCUtil.encrypt(passwordBefor, AESCBCUtil.AESCBC_HEX);
        final String userName = AESCBCUtil.encrypt(usernameStr, AESCBCUtil.AESCBC_HEX);
        MeDao.getInstance().getUserToken(application, userName, 0, 0, password, uuid, captchaCode, new BaseCallBack() {
            @Override
            public void success(Object data) {
                LoginInfo loginInfo = (LoginInfo) data;
                if (null != loginInfo.getMobile() && loginInfo.getMobile().length() > 0) {
                    loginInfo.setMobile(AESCBCUtil.decrypt(loginInfo.getMobile(), AESCBCUtil.AESCBC_HEX));
                }
                saveUserBaseInfo(loginInfo, application, isMobile, password, "", "", 0, true, "");
                //保存token信息到数据库
                LoginToken.saveTokenInfoToContentProividerByPad(application, loginInfo, null);
                saveTokenInfo(loginInfo);
                listener.onLoginSuccess(!TextUtils.isEmpty(loginInfo.getMobile()), passwordBefor);
                //上报登录信息
                FeedbackUtil.getInstance().asyncUploadUserLogin();
            }

            @Override
            public void failed(int errorCode, Object data) {

                listener.onLoginFiled(errorCode, String.valueOf(data));
            }

            @Override
            public void failed(Object data) {
                listener.onLoginFiled(data);
            }
        });

    }

    @Override
    public void loginByRealUserInfo(final EApplication application, final String usernameStr, final String realUserName, final long schoolId, final String schoolName, final String passwordBefor, String uuid, String captchaCode, final LoginFinishedListener listener, final boolean isMobile) {
        final String password = AESCBCUtil.encrypt(passwordBefor, AESCBCUtil.AESCBC_HEX);
        final String userName = AESCBCUtil.encrypt(usernameStr, AESCBCUtil.AESCBC_HEX);
        MeDao.getInstance().getUserToken(application, userName, schoolId, 2, password, uuid, captchaCode, new BaseCallBack() {
            @Override
            public void success(Object data) {
                LoginInfo loginInfo = (LoginInfo) data;
                if (null != loginInfo.getMobile() && loginInfo.getMobile().length() > 0) {
                    loginInfo.setMobile(AESCBCUtil.decrypt(loginInfo.getMobile(), AESCBCUtil.AESCBC_HEX));
                }
                saveUserBaseInfo(loginInfo, application, isMobile, password, schoolName, userName, schoolId, false, realUserName);
                //保存token信息到数据库
                LoginToken.saveTokenInfoToContentProividerByPad(application, loginInfo, null);
                saveTokenInfo(loginInfo);
                listener.onLoginSuccess(!TextUtils.isEmpty(loginInfo.getMobile()), passwordBefor);
                //上报登录信息
                FeedbackUtil.getInstance().asyncUploadUserLogin();
            }

            @Override
            public void failed(int errorCode, Object data) {

                listener.onLoginFiled(errorCode, String.valueOf(data));
            }

            @Override
            public void failed(Object data) {
                listener.onLoginFiled(data);
            }
        });
    }

    private void saveUserBaseInfo(LoginInfo loginInfo, EApplication application, boolean isMobile, String password, String schoolName, String userName, long schoolId, boolean isQuickLogin, final String realUserName) {
        final UserInfoBase userInfoBase = new UserInfoBase();
        userInfoBase.setUserId(Long.parseLong(loginInfo.getUserId()));
        userInfoBase.setIsMobile(isMobile);
        userInfoBase.setAvatar(loginInfo.getAvatar());
        userInfoBase.setNickName(loginInfo.getNickName());
        userInfoBase.setMobile(loginInfo.getMobile());
        userInfoBase.setRealName(loginInfo.getRealName());
        application.setUserInfoBase(userInfoBase);
        EApplication.MOBILE = loginInfo.getMobile();
        final UserAccountInfo userAccountInfo = new UserAccountInfo();
        userAccountInfo.setPhoneNumber(loginInfo.getMobile());
        userAccountInfo.setPhonelogin(isMobile);
        userAccountInfo.setUserId(Long.parseLong(loginInfo.getUserId()));
        userAccountInfo.setUserPwd(password);
        userAccountInfo.setAvatar(loginInfo.getAvatar());
        userAccountInfo.setNickName(userName);
        userAccountInfo.setSchoolName(schoolName);
        userAccountInfo.setSchoolId(schoolId);
        userAccountInfo.setQuickLogin(isQuickLogin);
        userAccountInfo.setRealUserName(realUserName);

        try {

            CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_USER_INFO_BASE, userInfoBase);
            CWSys.setSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, userInfoBase.getUserId());

            //清除用户学习班级信息
            CWSys.setSharedSerializable(SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_SCHOOL + userInfoBase.getUserId(), null);
            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT, null);
            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST, null);
            application.setSchoolDetail(null);
            application.setClazz(null);
            application.setClazzs(null);

            CWSys.setSharedString(EConstants.SHARE_PRE_CURR_LOGIN_USER_PHONE + SerializableManager.getInstance().getUserId(true), userInfoBase.getMobile());


        } catch (IOException e) {
            e.printStackTrace();
        }
        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                new BaseCallBack() {
                    @Override
                    public void success(Object data) {
                        List<UserAccountInfo> userAccountList;
                        if (data instanceof List) {
                            userAccountList = (ArrayList<UserAccountInfo>) data;
                        } else {
                            userAccountList = new ArrayList<>();
                        }
                        if (EConstants.IS_YOUKE) {
                            //DO NOTHING
                        } else {
                            //将实名登录信息 保存至第一个
                            for (int i = 0; i < userAccountList.size(); i++) {
                                if (null != userAccountList.get(i).getSchoolName() && !"".equals(userAccountList.get(i).getSchoolName())
                                        && "".equals(userAccountInfo.getSchoolName())) {
                                    userAccountInfo.setSchoolName(userAccountList.get(i).getSchoolName());
                                    if (null != userAccountList.get(i).getNickName() && !"".equals(userAccountList.get(i).getNickName())) {
                                        userAccountInfo.setNickName(userAccountList.get(i).getNickName());
                                    }
                                    if (null != userAccountList.get(i).getRealUserName() && !"".equals(userAccountList.get(i).getRealUserName())) {
                                        userAccountInfo.setRealUserName(userAccountList.get(i).getRealUserName());
                                    }
                                    userAccountInfo.setSchoolId(userAccountList.get(i).getSchoolId());
                                    break;
                                }

                            }
                            for (int i = 0; i < userAccountList.size(); i++) {
                                if (userAccountList.get(i).getUserId() == userAccountInfo.getUserId()) {
                                    userAccountList.remove(i);
                                }
                            }
                            //如果是免密码登录，只记住一个用户名
                            if ("100151".equals(EConstants.CLIENT_ID)) {
                                userAccountList.clear();
                            }
                            userAccountList.add(0, userAccountInfo);
                            SerializableManager.getInstance().serialize(
                                    SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                                    (Serializable) userAccountList, false);
                        }


                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        createUerLoginList(userAccountInfo);
                    }

                    @Override
                    public void failed(Object data) {
                        createUerLoginList(userAccountInfo);
                    }

                }, false);

    }

    private void createUerLoginList(UserAccountInfo userAccountInfo) {
        if (EConstants.IS_YOUKE) {
            //DO NOTHING
        } else {
            List<UserAccountInfo> userInfoBaseList = new ArrayList<>();
            userInfoBaseList.add(userAccountInfo);
            SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                    (Serializable) userInfoBaseList, false);

            //
        }

    }

    public void saveTokenInfo(LoginInfo info) {
        BaseRequest.VerifyInfo verifyInfo = new BaseRequest.VerifyInfo();
        verifyInfo.setAccessToken(info.getAccessToken());
        verifyInfo.setClientId(EConstants.CLIENT_ID);
        verifyInfo.setClientIp(BaseApplication.getInstance().getAPP_IP());
        verifyInfo.setOauthVersion("2.0");
        verifyInfo.setScope("all");
        verifyInfo.setRefreshToken(info.getRefreshToken());
        verifyInfo.setExpiresIn(info.getExpiresIn());
        try {
            CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_VERITIFY_INFO,
                    verifyInfo);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            HttpRequest.setVerifyInfo(verifyInfo);
        }
    }
}
